package com.cheer.security;

import com.cheer.entity.User;
import com.cheer.enums.RoleEnum;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author cheer
 */
@Component
public class SpringSecurityUserInfoHolder implements UserInfoHolder {

    @Override
    public User getUser() {
        return ((CustomUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUser();
    }

    @Override
    public Long getUserId() {
        if (SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof CustomUserDetails) {
            return ((CustomUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUser().getId();
        }
        return null;
    }

    @Override
    public Boolean isUser() {
        return Objects.equals(RoleEnum.USER.getCode(), getUser().getRole());
    }

    @Override
    public Boolean isAdmin() {
        return Objects.equals(RoleEnum.ADMIN.getCode(), getUser().getRole());
    }
}
